import { wsConfig, wsEvents, wsStatus } from '@config/websocket';
import env from '@config/env';
import { mockChatMessages } from '@/mock/chatMessages';

class WebSocketService {
  constructor() {
    this.socket = null;
    this.status = wsStatus.DISCONNECTED;
    this.reconnectAttempts = 0;
    this.reconnectTimer = null;
    this.eventListeners = {};
    this.connected = false;
    this.mockMode = env.enableWsMock;
  }

  // 初始化连接
  connect() {
    if (this.mockMode) {
      this._initMockConnection();
      return;
    }

    this._initRealConnection();
  }

  // 初始化真实的WebSocket连接
  _initRealConnection() {
    if (this.socket) {
      this.disconnect();
    }

    this.status = wsStatus.CONNECTING;
    this._emitEvent(wsStatus.CONNECTING);

    try {
      this.socket = new WebSocket(wsConfig.baseUrl);

      this.socket.onopen = () => {
        this.status = wsStatus.CONNECTED;
        this.connected = true;
        this.reconnectAttempts = 0;
        this._emitEvent(wsEvents.CONNECT);
        console.log('WebSocket connected');
      };

      this.socket.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          this._emitEvent(data.type, data.payload);
        } catch (error) {
          console.error('Error parsing WebSocket message:', error);
        }
      };

      this.socket.onclose = () => {
        this.connected = false;
        this.status = wsStatus.DISCONNECTED;
        this._emitEvent(wsEvents.DISCONNECT);
        this._reconnect();
        console.log('WebSocket disconnected');
      };

      this.socket.onerror = (error) => {
        this.status = wsStatus.FAILED;
        this._emitEvent(wsEvents.ERROR, error);
        console.error('WebSocket error:', error);
      };
    } catch (error) {
      this.status = wsStatus.FAILED;
      this._emitEvent(wsEvents.ERROR, error);
      this._reconnect();
      console.error('WebSocket connection error:', error);
    }
  }

  // 初始化模拟的WebSocket连接
  _initMockConnection() {
    this.status = wsStatus.CONNECTING;
    this._emitEvent(wsStatus.CONNECTING);

    // 模拟连接建立时间
    setTimeout(() => {
      this.status = wsStatus.CONNECTED;
      this.connected = true;
      this._emitEvent(wsEvents.CONNECT);
      console.log('Mock WebSocket connected');
    }, 500);
  }

  // 重新连接
  _reconnect() {
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
    }

    if (this.reconnectAttempts < wsConfig.maxReconnectAttempts) {
      this.status = wsStatus.RECONNECTING;
      this._emitEvent(wsStatus.RECONNECTING);
      
      this.reconnectTimer = setTimeout(() => {
        this.reconnectAttempts++;
        console.log(`Attempting to reconnect (${this.reconnectAttempts}/${wsConfig.maxReconnectAttempts})...`);
        this.connect();
      }, wsConfig.reconnectInterval);
    } else {
      this.status = wsStatus.FAILED;
      this._emitEvent(wsStatus.FAILED);
      console.error('Max reconnect attempts reached');
    }
  }

  // 断开连接
  disconnect() {
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
      this.reconnectTimer = null;
    }

    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.close();
    }

    this.status = wsStatus.DISCONNECTED;
    this.connected = false;
  }

  // 发送消息
  send(type, payload) {
    if (this.mockMode) {
      this._handleMockSend(type, payload);
      return;
    }

    if (!this.connected) {
      console.warn('Cannot send message: WebSocket not connected');
      return;
    }

    try {
      const message = JSON.stringify({ type, payload });
      this.socket.send(message);
    } catch (error) {
      console.error('Error sending WebSocket message:', error);
      this._emitEvent(wsEvents.ERROR, error);
    }
  }

  // 处理模拟发送
  _handleMockSend(type, payload) {
    switch (type) {
      case 'join_chat':
        this._mockJoinChat(payload);
        break;
      case 'send_message':
        this._mockSendMessage(payload);
        break;
      case 'typing':
        this._mockTyping(payload);
        break;
      default:
        console.log(`Mock handling for ${type} not implemented`);
    }
  }

  // 模拟加入聊天
  _mockJoinChat(payload) {
    const { chatId } = payload;
    
    // 延迟模拟网络延迟
    setTimeout(() => {
      // 查找模拟数据中的聊天历史
      const chatMessages = mockChatMessages[chatId] || [];
      
      // 发送聊天历史事件
      this._emitEvent(wsEvents.CHAT_HISTORY, {
        chatId,
        messages: chatMessages
      });
    }, 800);
  }

  // 模拟发送消息
  _mockSendMessage(payload) {
    const { chatId, message } = payload;
    
    // 1. 消息已送达确认 - 立即发送确认
    setTimeout(() => {
      this._emitEvent(wsEvents.MESSAGE_DELIVERED, {
        messageId: message.id,
        chatId,
        timestamp: new Date().toISOString()
      });
      
      // 2. 服务器已接收消息
      setTimeout(() => {
        this._emitEvent(wsEvents.MESSAGE_RECEIVED, {
          chatId,
          messageId: message.id,
          status: "received",
          statusText: "服务器已接收消息",
          timestamp: new Date().toISOString()
        });
        
        // 3. 服务器正在分析消息
        setTimeout(() => {
          this._emitEvent(wsEvents.MESSAGE_ANALYZING, {
            chatId,
            messageId: message.id,
            status: "analyzing",
            statusText: "正在分析您的问题",
            timestamp: new Date().toISOString()
          });
          
          // 4. 服务器正在规划解决方案
          setTimeout(() => {
            this._emitEvent(wsEvents.MESSAGE_PLANNING, {
              chatId,
              messageId: message.id,
              status: "planning",
              statusText: "正在规划解决方案",
              timestamp: new Date().toISOString()
            });
            
            // 5. 服务器正在执行解决方案
            setTimeout(() => {
              this._emitEvent(wsEvents.MESSAGE_EXECUTING, {
                chatId,
                messageId: message.id,
                status: "executing",
                statusText: "正在执行解决方案",
                timestamp: new Date().toISOString()
              });
              
              // 6. 服务器正在响应
              setTimeout(() => {
                this._emitEvent(wsEvents.MESSAGE_RESPONDING, {
                  chatId,
                  messageId: message.id,
                  status: "responding",
                  statusText: "正在生成响应",
                  timestamp: new Date().toISOString()
                });
                
                // 7. AI开始输入
                this._emitEvent(wsEvents.TYPING_START, {
                  chatId,
                  sender: this._getAiNameForChat(chatId)
                });
                
                // 8. 生成AI回复
                setTimeout(() => {
                  // 停止输入状态
                  this._emitEvent(wsEvents.TYPING_END, {
                    chatId,
                    sender: this._getAiNameForChat(chatId)
                  });
                  
                  // 发送AI回复
                  const aiResponse = {
                    id: Date.now().toString() + Math.floor(Math.random() * 1000).toString(),
                    type: 'system',
                    sender: this._getAiNameForChat(chatId),
                    content: this._generateAiResponse(message.content),
                    time: new Date().toISOString()
                  };
                  
                  // 发送新消息事件
                  this._emitEvent(wsEvents.NEW_MESSAGE, {
                    chatId,
                    message: aiResponse
                  });
                  
                  // 9. 处理完成
                  setTimeout(() => {
                    this._emitEvent(wsEvents.MESSAGE_COMPLETED, {
                      chatId,
                      messageId: message.id,
                      status: "completed",
                      statusText: "处理完成",
                      timestamp: new Date().toISOString()
                    });
                  }, 500);
                }, 1000);
              }, 800);
            }, 800);
          }, 800);
        }, 800);
      }, 300);
    }, 200);
  }

  // 生成AI回复
  _generateAiResponse(userMessage) {
    // 基于用户消息生成不同的回复，使回复看起来更加真实
    if (userMessage.toLowerCase().includes('hello') || userMessage.toLowerCase().includes('hi')) {
      return `您好！很高兴为您服务。有什么我可以帮助您的吗？`;
    } else if (userMessage.includes('?') || userMessage.includes('？')) {
      return `针对您的问题"${userMessage}"，我分析后认为：这需要从多个角度考虑。首先，我们需要明确问题的背景和具体需求。其次，基于已有信息，我建议可以从以下几个方面着手解决...`;
    } else if (userMessage.length < 10) {
      return `我已收到您的简短消息："${userMessage}"。需要更多信息才能提供有价值的帮助。能否详细描述一下您的需求或问题？`;
    } else {
      return `感谢您的详细描述。根据您提供的信息："${userMessage.substring(0, 20)}..."，我已完成分析并提出解决方案。首先，我们需要理清核心问题；其次，我推荐采用以下步骤解决；最后，请注意以下几点可能的风险和应对措施...`;
    }
  }

  // 模拟输入状态
  _mockTyping(payload) {
    const { chatId, isTyping } = payload;
    
    // 不需要特别处理，因为前端已经显示状态
    console.log(`Mock typing status: ${isTyping ? 'started' : 'stopped'} for chat ${chatId}`);
  }

  // 获取特定聊天的AI名称
  _getAiNameForChat(chatId) {
    const aiNames = ['DeepSeekV3', '星火认知大模型', 'GPT-4', 'Claude', 'Gemini', 'Qwen', 'Baichuan'];
    const index = parseInt(chatId.substring(0, 2), 16) % aiNames.length;
    return aiNames[index];
  }

  // 添加事件监听器
  on(event, callback) {
    if (!this.eventListeners[event]) {
      this.eventListeners[event] = [];
    }
    this.eventListeners[event].push(callback);
    
    // 返回取消监听的函数
    return () => this.off(event, callback);
  }
  
  // 移除事件监听器
  off(event, callback) {
    if (!this.eventListeners[event]) {
      return;
    }
    
    const index = this.eventListeners[event].indexOf(callback);
    if (index !== -1) {
      this.eventListeners[event].splice(index, 1);
    }
  }
  
  // 触发事件
  _emitEvent(event, payload) {
    if (!this.eventListeners[event]) {
      return;
    }
    
    this.eventListeners[event].forEach(callback => {
      try {
        callback(payload);
      } catch (error) {
        console.error(`Error in event listener for ${event}:`, error);
      }
    });
  }
  
  // 获取连接状态
  getStatus() {
    return this.status;
  }
  
  // 检查是否已连接
  isConnected() {
    return this.connected;
  }
}

// 导出单例
export default new WebSocketService(); 